package com.lfg.leetcode.leetcode500;


public class No714maxProfit {
    public static void main(String[] args) {

        System.out.println(maxProfit(new int[]{1, 3, 2, 8, 4, 9}, 2));
        System.out.println(maxProfit(new int[]{1,3,7,5,10,3}, 3));
        System.out.println(maxProfit(new int[]{1,3,5,7,9,11}, 2));
        System.out.println(maxProfit2(new int[]{1, 3, 2, 8, 4, 9}, 2));
        System.out.println(maxProfit2(new int[]{1,3,7,5,10,3}, 3));
        System.out.println(maxProfit2(new int[]{1,3,5,7,9,11}, 2));
    }

    public static int maxProfit(int[] prices, int fee) {

        int[][] dp = new int[prices.length][2];

        dp[0][0] = -prices[0]; // 持仓收益
        dp[0][1] = 0; // 空仓收益


        for (int i = 1; i < prices.length; i++) {
            dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1]-prices[i]);
            dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0]+prices[i]-fee);
        }

        return dp[prices.length-1][1];
    }


    public static int maxProfit2(int[] prices, int fee) {

      int buy = prices[0]+fee;
      int ret = 0;

        for (int i = 1; i < prices.length; i++) {
            int cost = prices[i] + fee;
            if(cost <buy){
                buy = cost;
            }else if(prices[i]>buy){
                ret+= prices[i] - buy;
                buy = prices[i];
            }
        }

        return ret;
    }
}



